package com.example.demo.controller;

import com.example.demo.entity.UserEntity;
import com.example.demo.services.CustomUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author rqian
 */
@Controller
public class LoginController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private CustomUserService userService;



    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerPage(Model model) {
        logger.info("enter register page.");
        model.addAttribute("userEntity", new UserEntity());
        return "register";
    }



    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@Validated UserEntity userEntity, BindingResult bindingResult, String role) {
        logger.info("Start register process.");
        if (bindingResult.hasErrors()) {
            logger.warn("User info has validation error.");
            return "register";
        }
        UserEntity savedUser = userService.saveUser(userEntity, role);
        if (null != savedUser) {
            logger.info("Create user success, redirect to login page.");
            return "/login";
        } else {
            logger.warn("Create user failed, redirect to register page.");
            return "register";
        }
    }

}
